package com.housekeeping.housekeeping.serviceItem.controller;

import com.alibaba.fastjson.JSONObject;
import com.housekeeping.housekeeping.serviceItem.entity.Img;
import com.housekeeping.housekeeping.serviceItem.utils.RequestUtils;
import com.housekeeping.housekeeping.serviceItem.utils.ResponseUtils;
import com.housekeeping.housekeeping.serviceItem.utils.StatUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@WebServlet("/ImgServlet/upload")
public class ImgController extends HttpServlet {
    private static String baseUrl;

    static {
        try {//客户端访问图片基础路径
            baseUrl = "http://" + InetAddress.getLocalHost().getHostAddress() + ":8080/img/";
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //文件上传对像
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置图片后缀组
        String[] allow = {".gif", ".jpeg", ".jpg", ".png", ".bmp"};
        //通过文件上传对象解析request
        try {
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem item : list) {
                //非文本字段
                if (!item.isFormField()) {   //判断是否为合法图片文件
                    String fileName = item.getName();
                    String suffix = fileName.substring(fileName.lastIndexOf("."));
                    //非法文件,返回错误信息
                    if (Arrays.binarySearch(allow, suffix) < 0) {
                        ResponseUtils.fail(resp, StatUtil.PARAMS_VALID);
                    } else {
                        //合法图片文件，保存至本地
                        String path = req.getServletContext().getRealPath("/img");
                        //判断文件目录是否存在
                        File file = new File(path);
                        if (!file.exists()) {
                            //不存在，则创建
                            file.mkdirs();
                        }
                        //存入目录
                        //获取输入流
                        InputStream in = item.getInputStream();
                        //获取输出流
                        //设置图片名
                        //储存图片名
                        String retFileName;
                        //获取上传账号id
                        String aid=RequestUtils.verify(req);
                        //已登录
                        if (aid!=null) {retFileName=UUID.randomUUID() + "_" +"["+aid+']'+ fileName;}
                        //未登录
                        else {retFileName=UUID.randomUUID() + "_" + fileName;}
                        File img = new File(path, retFileName);
                        FileOutputStream fos = new FileOutputStream(img);
                        IOUtils.copy(in, fos);
                        String storeUrl = img.getAbsolutePath();
                        //返回成功响应
                        ResponseUtils.success(resp, JSONObject.toJSONString(new Img(img.getName(), baseUrl + img.getName())), StatUtil.SUCCESS);
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            ResponseUtils.fail(resp, StatUtil.INTERNET_ERR);
        }
    }
}
